from django.shortcuts import render_to_response,RequestContext,HttpResponseRedirect,Http404
from blog.models import Blog,Author
from blog.forms import BlogForm

def blog_list(request):
    blogs=Blog.objects.all()
    return render_to_response('blog_list.html',{'blogs':blogs})

def blog_show(request,id=''):
    try:
        blog=Blog.objects.get(id=id)
    except Blog.DoesNotExist:
        raise Http404
    return render_to_response("blog_show.html",{"blog":blog})

def blog_add(request):
    if request.method=='POST':
        form=BlogForm(request.POST)
        if form.is_valid():
            cd=form.cleaned_data
            title=cd['caption']
            author=Author.objects.get(id=1)
            content=cd['content']
            blog=Blog(caption=title,author=author,content=content)
            blog.save()
            id=Blog.objects.order_by('-publish_time')[0].id
            return HttpResponseRedirect('/blog/blogshow/%s'%id)
    else:
        form=BlogForm()
        return render_to_response('blog_add.html',{'form':form},context_instance=RequestContext(request))

def blog_del(request,id=''):
    try:
        blog=Blog.objects.get(id=id)
    except:
        raise Http404
    if blog:
        blog.delete()
        return HttpResponseRedirect('/blog/bloglist')
    blogs=Blog.objects.all()
    return render_to_response('bloglist.html',{'blogs':blogs})

def blog_update(request,id=''):
    id = id
    if request.method=='POST':
        form =BlogForm(request.POST)
        if form.is_valid():
            cd =form.cleaned_data
            title=cd['caption']
            content=cd['content']
            blog=Blog.objects.get(id=id)
            if blog:
                blog.caption=title
                blog.content=content
                blog.save()
            else:
                blog=Blog(caption=blog.caption,content=blog.content)
                blog.save()
            return HttpResponseRedirect('/blog/blogshow/%s'%id)
    else:
        try:
            blog=Blog.objects.get(id=id)
        except:
            raise Http404
        form =BlogForm(initial={'caption':blog.caption,'content':blog.content},auto_id=False)
        return render_to_response('blog_add.html',{'blog':blog,'form':form,'id':id},context_instance=RequestContext(request))